package month1;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class BinaryTreeLevelOrderTravel102_05 {
    public static void main(String[] args) {
        System.out.println(levelOrder(new TreeNode(new Integer[]{3, 9, 20, null, null, 15, 7})));
    }

    /**
     * BFS 层序遍历
     * @param root
     * @return
     */
    static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ret = new LinkedList<>();
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while (root != null && !q.isEmpty()) {
            List<Integer> nodes = new LinkedList<>();
            for (int i = q.size(); i > 0; --i) {
                TreeNode node = q.poll();
                nodes.add(node.val);
                if (node.left != null) {
                    q.offer(node.left);
                }
                if (node.right != null) {
                    q.offer(node.right);
                }
            }
            ret.add(nodes);
        }
        return ret;
    }
}
